package com.example.dense_rack_server.controller;


import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.dense_rack_server.entity.Host;
import com.example.dense_rack_server.entity.Notice;
import com.example.dense_rack_server.entity.SysParamset;
import com.example.dense_rack_server.service.HostService;
import com.example.dense_rack_server.service.NoticeService;
import com.example.dense_rack_server.service.SysParamsetService;
import com.example.dense_rack_server.utils.DateFormat;
import com.example.dense_rack_server.utils.ResponseModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * <p>
 * 设备主机 前端控制器
 * </p>
 *
 * @author 张彬
 * @since 2025-03-05
 */
@Controller
@RequestMapping("/host")
public class HostController {

    private static final Logger log = LoggerFactory.getLogger(HostController.class);
    @Resource
    public HostService hostService;
    @Resource
    public NoticeService noticeService;
    @Resource
    public SysParamsetService sysParamsetService;

    /**
     * 温湿度
     */
    @GetMapping("/temperatureAndHumidity/index")
    public ModelAndView temperatureAndHumidityIndex() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("temperatureAndHumidity/index");

        Date nowDate = DateUtil.date();
        Date startDate = DateUtil.offset(nowDate, DateField.MONTH, -1);
        String startFormatDate = DateUtil.formatDate(startDate);
        String endFormatDate = DateUtil.formatDate(nowDate);
        modelAndView.addObject("startDate", startFormatDate);
        modelAndView.addObject("endDate", endFormatDate);
        return modelAndView;
    }


    /**
     * 获取设备信息
     */
    @GetMapping("/get/info")
    @ResponseBody
    public ResponseModel getHostInfo(@RequestParam(value = "hostId") int hostId) {
        Host host = hostService.getById(hostId);
        return ResponseModel.success(host);
    }


    /**
     * 获取区域列表
     */
    @GetMapping("/list")
    @ResponseBody
    public Map<String, Object> listTable(@RequestParam(value = "areaId", required = false) String areaId,
                                         @RequestParam(value = "page") int page,
                                         @RequestParam(value = "limit") int limit) {
        return hostService.listTable(areaId, page, limit);
    }

    /**
     * 档案区域密集架新增页面
     */
    @GetMapping("/denseRack/add")
    public ModelAndView addDenseRack() {
        ModelAndView modelAndView = new ModelAndView("sysParamset/addDenseRack");
        modelAndView.addObject("sysType", sysParamsetService.getOne(new QueryWrapper<SysParamset>().eq("id", 2)).getParamValue());
        return modelAndView;
    }


    /**
     * 档案区域密集架新增保存
     */
    @PostMapping("/denseRack/save")
    @ResponseBody
    public ResponseModel saveDenseRack(@RequestBody JSONObject data) {
        if (StrUtil.isEmpty(data.getStr("ip")) || StrUtil.isEmpty(data.getStr("cabinetJoint"))
                || StrUtil.isEmpty(data.getStr("cabinetLayer")) || StrUtil.isEmpty(data.getStr("rfidNumber"))) {
            return ResponseModel.fail("参数不能为空");
        }
        Host host = new Host();
        host.setIp(data.getStr("ip"));
        host.setCabinetName(data.getStr("cabinetName"));
        host.setCabinetNumber(data.getInt("cabinetNumber"));
        host.setOnlineStatus(0);
        host.setColumnNumber(data.getInt("columnNumber"));
        host.setCabinetJoint(data.getInt("cabinetJoint"));
        host.setCabinetLayer(data.getInt("cabinetLayer"));
        host.setRfidNumber(data.getInt("rfidNumber"));
//        host.setAreaId(data.getInt("areaId"));
        host.setCreateTime(DateFormat.getTime());
        host.setFixedColumn(data.getInt("fixedColumn"));
        // 排序
        List<String> keyList = new ArrayList<>();
        for (String key : data.keySet()) {
            if (key.startsWith("rfidColumn")) {
                keyList.add(key);
            }
        }
        keyList.sort(Comparator.naturalOrder());
        Map<String, Object> rfidMap = new LinkedHashMap<>();
        for (String key : keyList) {
            rfidMap.put(key, data.getStr(key));
        }
        host.setRfidList(JSONUtil.toJsonStr(rfidMap));

        boolean insertStatus = hostService.save(host);
        if (insertStatus) {
            // 添加通知
            List<Notice> columnList = new ArrayList<>();
            for (int i = 1; i <= data.getInt("columnNumber"); i++) {
                Notice notice = new Notice();
                notice.setNoticeContent("");
                notice.setCreateTime(DateFormat.getTime());
                notice.setUpdateTime(DateFormat.getTime());
                notice.setHostId(host.getId());
                notice.setColumnNumber(i);
                columnList.add(notice);
            }
            noticeService.saveBatch(columnList);
            return ResponseModel.success("新增密集架成功");
        } else {
            return ResponseModel.fail("新增密集架失败");
        }
    }


    /**
     * 档案区域密集架修改页面
     */
    @GetMapping("/denseRack/update/{id}")
    public ModelAndView updateDenseRack(@PathVariable("id") String id) {
        ModelAndView modelAndView = new ModelAndView("sysParamset/updateDenseRack");
        Host host = hostService.getById(id);
        modelAndView.addObject("host", host);
        List<Integer> columnList = new ArrayList<>();
        for (int column = 1; column <= host.getColumnNumber(); column++) {
            columnList.add(column);
        }
        modelAndView.addObject("columnList", columnList);
        modelAndView.addObject("sysType", sysParamsetService.getOne(new QueryWrapper<SysParamset>().eq("id", 2)).getParamValue());
        JSONObject rfidMap = JSONUtil.parseObj(host.getRfidList());
        modelAndView.addObject("rfidMap", rfidMap);
        return modelAndView;
    }


    /**
     * 档案区域密集架修改保存
     */
    @PostMapping("/denseRack/update/save")
    @ResponseBody
    public ResponseModel updateDenseRackSave(@RequestBody JSONObject data) {
        if (StrUtil.isEmpty(data.getStr("ip"))
                || StrUtil.isEmpty(data.getStr("cabinetJoint"))
                || StrUtil.isEmpty(data.getStr("cabinetLayer")) || StrUtil.isEmpty(data.getStr("rfidNumber"))) {
            return ResponseModel.fail("参数不能为空");
        }
        UpdateWrapper<Host> queryWrapper = new UpdateWrapper<>();
        queryWrapper.eq("id", data.getInt("id"));
        queryWrapper.set("ip", data.getStr("ip"));
        queryWrapper.set("cabinet_name", data.getStr("cabinetName"));
        queryWrapper.set("cabinet_number", data.getStr("cabinetNumber"));
        queryWrapper.set("column_number", data.getStr("columnNumber"));
        queryWrapper.set("cabinet_joint", data.getStr("cabinetJoint"));
        queryWrapper.set("cabinet_layer", data.getStr("cabinetLayer"));
        queryWrapper.set("rfid_number", data.getStr("rfidNumber"));
        queryWrapper.set("fixed_column", data.getStr("fixedColumn"));
        // 排序
        List<String> keyList = new ArrayList<>();
        for (String key : data.keySet()) {
            if (key.startsWith("rfidColumn")) {
                keyList.add(key);
            }
        }
        keyList.sort(Comparator.naturalOrder());
        Map<String, Object> rfidMap = new LinkedHashMap<>();
        for (String key : keyList) {
            rfidMap.put(key, data.getStr(key));
        }
        queryWrapper.set("rfid_list",JSONUtil.toJsonStr(rfidMap));

        boolean updateStatus = hostService.update(queryWrapper);
        if (updateStatus) {
            return ResponseModel.success("修改密集架成功");
        } else {
            return ResponseModel.fail("修改密集架失败");
        }
    }

    /**
     * 密集架设备删除
     */
    @DeleteMapping("/delete/host/{hostId}")
    @ResponseBody
    public ResponseModel deleteHost(@PathVariable("hostId") String hostId) {
        boolean deleteStatus = hostService.removeById(Convert.toInt(hostId));
        if (deleteStatus) {
            return ResponseModel.success("删除密集架成功");
        } else {
            return ResponseModel.fail("删除密集架失败");
        }
    }

}
